<!DOCTYPE html>
<html>
<head>
    <title>销售统计分析</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .stat-container {
            max-width: 1600px;
            margin: 20px auto;
            padding: 20px;
        }
        .filter-panel {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .data-table {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .table-header {
            background-color: #c0a36c;
            color: white;
            padding: 15px 20px;
        }
        .table-container {
            overflow-x: auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        /* 序号列 - 缩小 */
        th:nth-child(1), td:nth-child(1) {
            width: 60px;
            min-width: 60px;
            max-width: 60px;
        }
        /* 销售日期列 */
        th:nth-child(2), td:nth-child(2) {
            width: 120px;
            min-width: 120px;
            max-width: 120px;
        }
        /* 买家名列 */
        th:nth-child(3), td:nth-child(3) {
            width: 100px;
            min-width: 100px;
            max-width: 100px;
        }
        /* 销售数量列 */
        th:nth-child(4), td:nth-child(4) {
            width: 100px;
            min-width: 100px;
            max-width: 100px;
        }
        /* 销售金额列 */
        th:nth-child(5), td:nth-child(5) {
            width: 120px;
            min-width: 120px;
            max-width: 120px;
        }
        /* 销售明细清单特定列样式 */
        /* 确保所有列名字体大小一致 */
        #statTable th {
            font-size: 14px;
        }
        /* 库存编号列 - 列宽加长 */
        #statTable th:nth-child(3), #statTable td:nth-child(3) {
            width: 180px;
            min-width: 180px;
            max-width: 180px;
            font-size: 13px;
        }
        /* 销售数量列 - 缩短，左对齐 */
        #statTable th:nth-child(5), #statTable td:nth-child(5) {
            width: 80px;
            min-width: 80px;
            max-width: 80px;
            text-align: left;
        }
        /* 总销售成本列 - 左对齐 */
        #statTable th:nth-child(6), #statTable td:nth-child(6) {
            text-align: left;
        }
        /* 实际销售金额列 - 左对齐 */
        #statTable th:nth-child(7), #statTable td:nth-child(7) {
            text-align: left;
        }
        /* 利润列 - 左对齐 */
        #statTable th:nth-child(8), #statTable td:nth-child(8) {
            width: 90px;
            min-width: 90px;
            max-width: 90px;
            text-align: left;
        }
        /* 买家名列 */
        #statTable th:nth-child(9), #statTable td:nth-child(9) {
            width: 100px;
            min-width: 100px;
            max-width: 100px;
        }
        /* 买家公司列 - 加长 */
        #statTable th:nth-child(10), #statTable td:nth-child(10) {
            width: 150px;
            min-width: 150px;
            max-width: 150px;
        }
        
        /* 按日+买家分类汇总特定样式 */
        /* 销售件数列 - 居中对齐 */
        #statTable.daily-buyer th:nth-child(4), 
        #statTable.daily-buyer td:nth-child(4) {
            text-align: center;
        }
        /* 销售金额列 - 居中对齐 */
        #statTable.daily-buyer th:nth-child(5), 
        #statTable.daily-buyer td:nth-child(5) {
            text-align: center;
        }
        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #333;
        }
        tr:hover {
            background-color: #f8f9fa;
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        .error {
            color: #d32f2f;
            padding: 15px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 10px 0;
        }
        .action-btn {
            background-color: #c0a36c;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .action-btn:hover {
            background-color: #a88c5a;
        }
        .price-cell {
            text-align: right;
            font-family: monospace;
        }
        .summary-panel {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .summary-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            padding: 8px;
            background-color: white;
            border-radius: 4px;
        }
        .summary-label {
            font-weight: 600;
            color: #333;
        }
        .summary-value {
            font-weight: 600;
            color: #c0a36c;
        }
        .product-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
        }
    </style>
</head>
<body style="background-color:#fffbf6">
    
    <!-- 状态栏 -->
    {% include 'status_bar.html' %}
    
    <!-- 返回主菜单按钮 -->
    <div style="max-width: 1600px; margin: 20px auto 10px auto; padding: 0 20px;">
        <a href="/ej_index" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 10px;">
            <i class="bi bi-arrow-left"></i> 返回主菜单
        </a>
    </div>
    
    <div class="stat-container">
        <h2>销售统计分析</h2>

        <!-- 筛选面板 -->
        <div class="filter-panel">
            <div class="row">
                <div class="col-md-8">
                    <h5>统计条件设置</h5>
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label">开始日期</label>
                            <input type="date" class="form-control" id="startDate">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">结束日期</label>
                            <input type="date" class="form-control" id="endDate">
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <label class="form-label">统计类型</label>
                            <select class="form-control" id="statType">
                                <option value="daily_buyer">按日+买家分类汇总</option>
                                <option value="detail_list">销售明细清单</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div style="display: flex; gap: 10px; align-items: end; height: 100%;">
                        <button class="action-btn" onclick="loadSalesStat()">
                            <i class="bi bi-calculator"></i> 生成统计
                        </button>
                        <button class="action-btn" id="exportBtn" style="display: none;" onclick="exportDailyXlsx()">
                            <i class="bi bi-file-earmark-excel"></i> 导出Excel
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div id="loading" class="loading" style="display: none;">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p>正在生成统计数据...</p>
        </div>

        <div id="error" class="error" style="display: none;"></div>

        <!-- 汇总信息面板 -->
        <div id="summaryPanel" class="summary-panel" style="display: none;">
            <h5>统计汇总</h5>
            <div class="summary-item">
                <span class="summary-label">统计期间:</span>
                <span class="summary-value" id="summaryPeriod"></span>
            </div>
            <div class="summary-item">
                <span class="summary-label">总销售件数:</span>
                <span class="summary-value" id="summaryTotalQty"></span>
            </div>
            <div class="summary-item">
                <span class="summary-label">总销售金额:</span>
                <span class="summary-value" id="summaryTotalAmount"></span>
            </div>
            <div class="summary-item">
                <span class="summary-label">总销售成本:</span>
                <span class="summary-value" id="summaryTotalCost"></span>
            </div>
            <div class="summary-item">
                <span class="summary-label">总利润:</span>
                <span class="summary-value" id="summaryTotalProfit"></span>
            </div>
        </div>

        <!-- 数据表格 -->
        <div class="data-table">
            <div class="table-header">
                <h5 style="margin: 0;" id="tableTitle">销售统计数据列表</h5>
            </div>
            <div class="table-container">
                <table id="statTable">
                    <thead id="statTableHeader">
                        <!-- 表头将通过JavaScript动态生成 -->
                    </thead>
                    <tbody id="statTableBody">
                        <!-- 数据将通过JavaScript动态填充 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="../static/js/common.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 设置默认日期（最近30天）
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(startDate.getDate() - 30);
            
            document.getElementById('startDate').value = startDate.toISOString().split('T')[0];
            document.getElementById('endDate').value = endDate.toISOString().split('T')[0];
        });

        // 加载销售统计数据
        function loadSalesStat() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            const statType = document.getElementById('statType').value;
            
            if (!startDate || !endDate) {
                alert('请选择开始日期和结束日期');
                return;
            }
            
            if (new Date(startDate) > new Date(endDate)) {
                alert('开始日期不能晚于结束日期');
                return;
            }

            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            const summaryPanel = document.getElementById('summaryPanel');
            
            loading.style.display = 'block';
            error.style.display = 'none';
            summaryPanel.style.display = 'none';

            const params = new URLSearchParams({
                start_date: startDate,
                end_date: endDate,
                stat_type: statType
            });

            fetch(`/get_sale_stat_data?${params}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    loading.style.display = 'none';
                    if (data.success && data.data) {
                        renderStatTable(data.data, statType);
                        updateSummaryPanel(data.summary, startDate, endDate);
                    } else {
                        throw new Error(data.message || '数据格式错误');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '加载统计数据失败: ' + error.message;
                });
        }

        // 更新汇总信息面板
        function updateSummaryPanel(summary, startDate, endDate) {
            if (!summary) return;
            
            document.getElementById('summaryPeriod').textContent = `${startDate} 至 ${endDate}`;
            document.getElementById('summaryTotalQty').textContent = formatInteger(summary.total_qty || 0);
            document.getElementById('summaryTotalAmount').textContent = '¥' + formatNumber(summary.total_amount || 0);
            document.getElementById('summaryTotalCost').textContent = '¥' + formatNumber(summary.total_cost || 0);
            document.getElementById('summaryTotalProfit').textContent = '¥' + formatNumber(summary.total_profit || 0);
            
            document.getElementById('summaryPanel').style.display = 'block';
        }

        // 渲染统计数据表格
        function renderStatTable(data, statType) {
            const tableHeader = document.getElementById('statTableHeader');
            const tableBody = document.getElementById('statTableBody');
            const tableTitle = document.getElementById('tableTitle');
            
            tableHeader.innerHTML = '';
            tableBody.innerHTML = '';

            if (data.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="20" style="text-align: center; padding: 20px; color: #666;">
                            没有找到匹配的销售数据
                        </td>
                    </tr>
                `;
                return;
            }

            if (statType === 'daily_buyer') {
                // 按日+买家分类汇总
                tableTitle.textContent = '按日+买家分类汇总';
                // 添加特定CSS类用于样式区分
                document.getElementById('statTable').className = 'daily-buyer';
                tableHeader.innerHTML = `
                    <tr>
                        <th>序号</th>
                        <th>销售日期</th>
                        <th>买家姓名</th>
                        <th>销售件数</th>
                        <th>销售金额</th>
                    </tr>
                `;

                data.forEach((item, index) => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${index + 1}</td>
                        <td>${formatDate(item.sale_date)}</td>
                        <td>${item.buyer_name || '未知买家'}</td>
                        <td class="price-cell">${formatInteger(item.total_qty)}</td>
                        <td class="price-cell">¥${formatNumber(item.total_amount)}</td>
                    `;
                    tableBody.appendChild(row);
                });
            } else if (statType === 'detail_list') {
                // 销售明细清单
                tableTitle.textContent = '销售明细清单';
                // 移除daily-buyer类，确保样式不冲突
                document.getElementById('statTable').className = '';
                tableHeader.innerHTML = `
                    <tr>
                        <th>序号</th>
                        <th>销售日期</th>
                        <th>库存编号</th>
                        <th>产品图片</th>
                        <th>销售数量</th>
                        <th>总销售成本</th>
                        <th>实际销售金额</th>
                        <th>利润</th>
                        <th>买家姓名</th>
                        <th>买家公司</th>
                    </tr>
                `;

                data.forEach((item, index) => {
                    const row = document.createElement('tr');
                    const profit = (parseFloat(item.sale_real_price || 0) - parseFloat(item.total_cost || 0)).toFixed(2);
                    const profitClass = profit >= 0 ? 'text-success' : 'text-danger';
                    
                    row.innerHTML = `
                        <td>${index + 1}</td>
                        <td>${formatDate(item.sale_datetime)}</td>
                        <td>${item.stock_id || ''}</td>
                        <td>
                            ${item.product_id ? 
                                `<img src="/serve_jade_image?product_id=${item.product_id}" 
                                      class="product-image" 
                                      alt="${item.stock_id}" 
                                      onerror="this.src='../static/images/default_cover.jpg'">` : 
                                '<img src="../static/images/default_cover.jpg" class="product-image" alt="默认图片">'}
                        </td>
                        <td class="price-cell">${formatInteger(item.sale_qty)}</td>
                        <td class="price-cell">¥${formatNumber(item.total_cost)}</td>
                        <td class="price-cell">¥${formatNumber(item.sale_real_price)}</td>
                        <td class="price-cell ${profitClass}">¥${formatNumber(profit)}</td>
                        <td>${item.buyer_name || ''}</td>
                        <td>${item.buyer_company || ''}</td>
                    `;
                    tableBody.appendChild(row);
                });
            }
        }

        // 格式化日期（仅日期部分）
        function formatDate(dateStr) {
            if (!dateStr) return '';
            const date = new Date(dateStr);
            return date.toLocaleDateString('zh-CN');
        }

        // 格式化日期时间
        function formatDateTime(dateTimeStr) {
            if (!dateTimeStr) return '';
            const date = new Date(dateTimeStr);
            return date.toLocaleString('zh-CN');
        }

        // 格式化数字（保留2位小数）
        function formatNumber(num) {
            if (num === null || num === undefined) return '0.00';
            return parseFloat(num).toFixed(2);
        }

        // 格式化整数（去掉小数部分）
        function formatInteger(num) {
            if (num === null || num === undefined) return '0';
            return parseInt(num).toString();
        }

        // 导出按日+买家分类汇总数据到Excel
        function exportDailyXlsx() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            const statType = document.getElementById('statType').value;
            
            if (!startDate || !endDate) {
                alert('请选择开始日期和结束日期');
                return;
            }
            
            if (statType !== 'daily_buyer') {
                alert('导出功能仅适用于"按日+买家分类汇总"统计类型');
                return;
            }

            // 构建导出URL
            const params = new URLSearchParams({
                start_date: startDate,
                end_date: endDate
            });

            // 创建下载链接并触发下载
            const downloadLink = document.createElement('a');
            downloadLink.href = `/export_daily_xlsx?${params}`;
            downloadLink.download = `销售汇总_${startDate}_至_${endDate}.xlsx`;
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
        }

        // 根据统计类型显示/隐藏导出按钮
        function toggleExportButton(statType) {
            const exportBtn = document.getElementById('exportBtn');
            if (statType === 'daily_buyer') {
                exportBtn.style.display = 'block';
            } else {
                exportBtn.style.display = 'none';
            }
        }

        // 监听统计类型变化
        document.getElementById('statType').addEventListener('change', function() {
            toggleExportButton(this.value);
        });

        // 页面加载时初始化导出按钮状态
        document.addEventListener('DOMContentLoaded', function() {
            toggleExportButton(document.getElementById('statType').value);
        });
    </script>
</body>
</html>
